<template>
  <!-- 卡片 -->
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showTrademark">添加</el-button>
      </div>
    </template>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="trademarkList" border style="width: 100%">
      <el-table-column type="index" align="center" label="序号" width="80" />
      <el-table-column align="center" prop="tmName" label="品牌名称" width="180" />
      <el-table-column align="center" label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width:100px;height: 60px;">
        </template>
      </el-table-column>
      <el-table-column align="center" prop="address" label="操作" width="180">
        <template v-slot="{ row }">
          <el-button type="warning" title="编辑品牌" :icon="Edit" size="small"
            @click="updateTrademarkInfo(row)"></el-button>
          <el-button type="danger" title="删除品牌" :icon="Delete" size="small" @click="delTrademarkInfo(row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="`${trademarkForm.id ? '编辑' : '添加'}品牌`">
      <el-form :model="trademarkForm"  ref="ruleFormRef" :rules="rules">
        <el-form-item prop="tmName" label="品牌名称" :label-width="formLabelWidth">
          <el-input v-model="trademarkForm.tmName" autocomplete="off" style="width:70%" />
        </el-form-item>
        <el-form-item prop="logoUrl" label="品牌LOGO" :label-width="formLabelWidth">
          <!-- 上传图片 -->
          <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/upload`" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="trademarkForm.logoUrl" :src="trademarkForm.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip text-red">
                只能上传jpg/png文件,且不超过2M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分页器 -->
    <el-pagination style="margin-top:20px" v-model:current-page="currentPage4" v-model:page-size="pageSize4"
      :page-sizes="[3, 5, 8, 10]" :small="small" :disabled="disabled" :background="background"
      layout=" prev, pager, next, jumper,->,total, sizes," :total=total @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </el-card>

</template>

<script lang="ts">
export default {
  name: "trademark",

}
</script>

<script setup lang="ts">
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'
import { reqGetAllTrademarkListData, reqSaveTrademarkData, reqDelTrademarkData,reqUpdateTrademarkData } from "@/api/product/trademark"
import type { TrademarkListModel, TrademarkModel } from "@/api/product/model/trademarkModel"
import type { UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

// loading加载效果
const loading = ref(true)

// 表格数据
const trademarkList = ref<TrademarkListModel>([])

// 对话框数据
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

// const from = reactive({tmName: '',logoUrl: ''})
const initTrademarkForm = () => ({ tmName: '', logoUrl: '' })
const trademarkForm = reactive<TrademarkModel>(initTrademarkForm())

// 上传图片需要的数据
const imageUrl = ref('')
const BASE_URL = import.meta.env.VITE_API_URL;

// 上传图片触发的事件
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  // 将图片在服务器的地址保存
  trademarkForm.logoUrl = response.data
  // 清空验证
  ruleFormRef.value?.clearValidate()
}
// 上传之前需要验证图片格式
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgurlType = ['image/jpeg', 'image/gif', 'image/jpg']
  // 如果上传的图片类型不包括在imgurlType中
  if (!imgurlType.includes(rawFile.type)) {
    ElMessage.error('上传的图片必须是jepg、gif、jpg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的图片格式不能大于2M!')
    return false
  }
  return true
}

// 上传数据的校验规则
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '输入不能为空', trigger: 'blur' },
    { min: 2, max: 5, message: '输入字符的长度须在2-5之间', trigger: 'blur' },
  ],
  logoUrl: [
    {
      required: true,
      message: '上传正确格式的图片',
      trigger: 'change',
    },
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 符合验证规则 触发添加/修改事件
      saveTrademarkInfo()
    } else {
      console.log('error submit!', fields)
    }
  })
}




// 生命周期函数
onMounted(() => {
  // 发送请求获取数据
  getTrademarkData()
})

// 1.发送请求 获取品牌管理 数据
const getTrademarkData = async () => {
  let result = await reqGetAllTrademarkListData(currentPage4.value, pageSize4.value)
  // console.log(result)
  ElMessage.success("获取品牌管理数据成功！")
  // 设置数据
  trademarkList.value = result.records
  // 设置总条数
  total.value = result.total
  // 数据加载完毕后关闭loading效果
  loading.value = false
}
// 2.点击 对话框的 确定 按钮  发送请求 添加/修改 品牌管理 数据
const saveTrademarkInfo = async () => {
  // 根据传入参数是否有id来判断是为添加还是编辑
  // 有id则视为编辑数据
  if(trademarkForm.id){
    await reqUpdateTrademarkData(trademarkForm)
  }else{
    // 没有id则视为添加数据
    await reqSaveTrademarkData(trademarkForm)
  }
  
  ElMessage({
    type: "success",
    message: "操作数据成功！"
  })
  // 关闭对话框
  dialogFormVisible.value = false
 
  // 跳转到第一页
  currentPage4.value = 1
  // 重新发送请求
  getTrademarkData()

}
// 3.点击 +添加 按钮 显示对话框 并清空上一次添加数据
const showTrademark = () => {
  // 显示对话框
  dialogFormVisible.value = true
   // 清空数据 id
   delete trademarkForm.id
  // 清空数据
  Object.assign(trademarkForm, initTrademarkForm())
  // 清空验证
  ruleFormRef.value?.clearValidate()
}
// 4. 点击 删除icon 弹出模态框 
const delTrademarkInfo = (row: TrademarkModel) => {
  ElMessageBox.confirm(
    `确认删除${row.tmName}品牌数据吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 发送请求删除数据
      await reqDelTrademarkData(row.id as number)
      ElMessage({
        type: 'success',
        message: '删除成功！',
      })
      // 重新发送请求
      getTrademarkData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除！',
      })
    })

}
// 5.点击 编辑icon 弹出模态框 并数据回显
const updateTrademarkInfo = (row: TrademarkModel) => {
  // 显示对话框
  dialogFormVisible.value = true
  //  数据回显
  Object.assign(trademarkForm,row)
  // 清空验证
  ruleFormRef.value?.clearValidate()
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>